import requests
from bs4 import BeautifulSoup
from lxml import etree
import schedule
from email.mime.text import MIMEText    #定义邮件内容
from email.header import Header     #定义邮件标题
import smtplib
import time

def get_html():
    headers={
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0',
        'Cookie': '_s_tentry=www.baidu.com; UOR=www.baidu.com,s.weibo.com,www.baidu.com; Apache=4230465232356.5806.1615092683337; SINAGLOBAL=4230465232356.5806.1615092683337; ULV=1615092683403:1:1:1:4230465232356.5806.1615092683337:; WBStorage=8daec78e6a891122|undefined',
        'Referer': 'https://www.baidu.com/link?url=ccq5LbfxJNECAW5-ucJRCAkcYlFXzxN6obYjxAR5pEMh_ASUx2BCXWkm_fE5aTlKX4fxyiKPqfVKM4aNmNbWuK&wd=&eqid=8c4b111a0013466f0000000260445bc7'

    }

    url='https://s.weibo.com/top/summary?cate=realtimehot'

    html=requests.get(url,headers=headers)

    return html.text
#获取信息
def masge():
    html=get_html()
    soup=BeautifulSoup(html,'lxml')

    titles=soup.select('div.data tbody tr')
    send_msgs=[]
    for title in titles:
        mark=title.select_one('.td-01').text
        biaoti=title.select_one('.td-02 a').text
        biaoqian=title.select_one('.td-03').text
        link=title.select_one('.td-02 a')['href']
        lianjie='https://s.weibo.com{}'.format(link)


        send_msgs.append((mark,biaoti,biaoqian,lianjie))

    #print(send_msgs)
    return send_msgs


#编辑邮件并发送
def send_email():
    rq = time.strftime("%Y-%m-%d-%X")  # 发送时间
    from_addr = "发送账号"  # 发送的邮箱
    smtpserver = "smtp.163.com"  # 发送邮箱SMTP服务器地址
    password = "密码"  # 密码，填写自己的密码即可，163邮箱和网页登录的邮箱不同
    # 接收邮箱的账号
    to_addr = "接收账号"
    to_addrs = ["接收账号", from_addr]

    # 邮件的标题
    subject = f"{rq} 微博热搜"
    # 邮件html内容，需要把热搜的爬取到的数据进行格式化
    data = masge()
    table = "<table>"
    for item in data:
        table += f'<tr><td><a href="{item[3]}">{item[0]} {item[1]} {item[2]}</a></td></tr>'
    table += "</table>"
    content = table
    msg = MIMEText(content, 'html', 'utf-8')  # 邮件的正文
    msg['Subject'] = Header(subject, 'utf-8')  # 邮件的标题
    msg['From'] = from_addr  # 邮件发送方
    msg['To'] = to_addr  # 邮件接收方，发送给一人
    # msg['To']=','.join(to_addrs)# 邮件接收方，发送给多人

    smtp = smtplib.SMTP_SSL(smtpserver, 465)  # SSL协议端口号要使用465
    smtp.helo(smtpserver)  # helo向邮箱标识用户身份
    smtp.ehlo(smtpserver)  # 服务器返回结果确认
    smtp.login(from_addr, password)  # 登录邮箱服务器，输入自己的账号和密码
    print("热搜发送中...")
    # smtp.sendmail(user,to_addrs,msgroot.as_string())# 邮件发送多人
    smtp.sendmail(from_addr, to_addr, msg.as_string())  # 发送给个人的邮件
    smtp.quit()
    print("发送完毕")

#send_email()


#定时发送设置
schedule.every(10).minutes.do(send_email)       #先设置定时时间

while True:
    schedule.run_pending()      #while循环，是去检查上面的任务部署情况，如果任务已经准备就绪，就去启动执行。t
    time.sleep(1)               #ime.sleep(1)是让程序按秒来检查，如果检查太快，会浪费计算机的资源。
    
    
    
